cURL / Mailing Lists / curl-library / Single Mail

curl-library

Re: rfc: curl_easy_setopt() typechecker

From: Nathan E. Moore <nate_at_redtetrahedron.org>
Date: Tue, 26 Feb 2008 02:25:54 -0500

--On Monday, February 25, 2008 3:11 PM +0100 Michal Marek <mmarek_at_suse.cz>
wrote:

> - __builtin_types_compatible_p() only works in C, not C++, so for C++
> there's no typechecking. Although it might be doable using rtti.
> - It only works with the not-yet-released gcc 4.3.

Argument type checking for C++ can be done via templates without RTTI or
any other runtime overhead. This is the basic technique:

namespace {
  template <bool> struct STATIC_ASSERTION;
  template <> struct STATIC_ASSERTION<true>{};
}
#define PASTE2(x, y) x ## y
#define PASTE(x, y) PASTE2(x, y)
#define ANON_VAR(unique) PASTE(unique, __LINE__)
#define STATIC_ASSERT(boolean) STATIC_ASSERTION<boolean>
ANON_VAR(static_assert)

#define INT_ARG 0
#define DOUBLE_ARG 1
#define CONST_CHAR_PTR_ARG 2

template<int t_flag, typename Arg>
void vawrapper(Arg)
{
   // need static assert here or you just get an error at link time
   STATIC_ASSERT(false);
}

template<> void vawrapper<INT_ARG, int>(int) {}

template<> void vawrapper<DOUBLE_ARG, double>(double) {}

template<> void vawrapper<CONST_CHAR_PTR_ARG, char const*>(char const*) {}

#define va(flag, arg) vawrapper<flag>(arg)

int main()
{
   va(INT_ARG, 1);
   va(DOUBLE_ARG, 1.0);
   va(CONST_CHAR_PTR_ARG, "str");

   //va(INT_ARG, 1.0); // FAIL
   //va(INT_ARG, 1L); // FAIL
   //va(INT_ARG, static_cast<short>(1)); // FAIL

}

Nathan Moore
Received on 2008-02-26