C
chrisstankevitz
Hi,
Q1: Is there a way to make a template function that works only for
specific types which produces a compiler error if used with an invalid
type?
Q2: If not, how do people deal with this issue?
I believe A1 is no. I tried below with template function "f".
For A2, functors work but have ugly syntax and runtime overhead. A
dispatcher to the funtor has nice syntax but still the overhead. I'm
just guessing about the overhead, but I believe there is a ctor.
Thanks,
Chris
//==========
// f: template function defined only for char
template<typename T>
void f(T t);
template<>
void f(char i)
{
// ...
}
// g: template functor defined only for char
template<typename T>
struct g;
template<>
struct g<char>
{
void operator()(char i)
{
// ...
}
};
// h: dispatcher to g
template<typename T>
void h(T t)
{
g<T>()(t);
}
int main()
{
char c;
long l;
// f - template function w/specialization
// syntax: clean
// runtime: fast
// compiler error on invalid type: no (but linker error)
f(c);
f(l);
// g - template class w/specialization
// syntax: ugly
// runtime: slow
// compiler error on invalid type: yes
g<char>()(c);
g<long>()(l);
// h - Dispatcher function calling g
// syntax: clean
// runtime: slow
// compiler error on invalid type: yes (albeit cryptic)
h(c);
h(l);
return 0;
}
Q1: Is there a way to make a template function that works only for
specific types which produces a compiler error if used with an invalid
type?
Q2: If not, how do people deal with this issue?
I believe A1 is no. I tried below with template function "f".
For A2, functors work but have ugly syntax and runtime overhead. A
dispatcher to the funtor has nice syntax but still the overhead. I'm
just guessing about the overhead, but I believe there is a ctor.
Thanks,
Chris
//==========
// f: template function defined only for char
template<typename T>
void f(T t);
template<>
void f(char i)
{
// ...
}
// g: template functor defined only for char
template<typename T>
struct g;
template<>
struct g<char>
{
void operator()(char i)
{
// ...
}
};
// h: dispatcher to g
template<typename T>
void h(T t)
{
g<T>()(t);
}
int main()
{
char c;
long l;
// f - template function w/specialization
// syntax: clean
// runtime: fast
// compiler error on invalid type: no (but linker error)
f(c);
f(l);
// g - template class w/specialization
// syntax: ugly
// runtime: slow
// compiler error on invalid type: yes
g<char>()(c);
g<long>()(l);
// h - Dispatcher function calling g
// syntax: clean
// runtime: slow
// compiler error on invalid type: yes (albeit cryptic)
h(c);
h(l);
return 0;
}