开发者

Downcasting in templates

Why when having:

template<double&& value>
struct X
{
};

this doesn't work:

X<1> not_ok;

but this works:

X<1.0> ok;  

Shouldn't there be orthogonality in behaviour? If I can pass an int into fnc taking double as an arg why cannot I do it with <> (template)? Is there any way to bypass this (I need this to make one template (instead of two with different names) which will allow me to either take double&& or int&&)? I tried to pass class which conversion ctor from int to this class but this crashes VS compiler. I don't know what to do. I'm stuck. I also tried specialization:

template<class T>
struct X;

template<>
struct X<double&&>
{
};

templat开发者_StackOverflowe<>
struct X<int&&>
{
};

but surprise surprise doesn't work. Why? I have a primary template and then I want to specialize it on certain types, why doesn't it work?


According to N3126 (the final draft) (14.1/4):

A non-type template-parameter shall have one of the following (optionally cv-qualified) types:

  • integral or enumeration type,
  • pointer to object or pointer to function,
  • lvalue reference to object or lvalue reference to function, (emphasis mine)
  • pointer to member.

So, as you can see, rvalue refernces are not permitted at all as template parameters. If you want to overcome the limitation that template parameters can't be doubles, why don't you express your load factor as a rational:

my_vector<7, 12> ... load factor at least 7/12.

BTW you could just as well store the load factor as a constant (or as member) which would probably give you less code bloat and not much worse performance.

The second problem you posted (specialization for double&&) is a totally different thing, is supported and works for me (with g++-4.5):

template<class T>
struct X;

template<>
struct X<double&&>
{
};

template<>
struct X<int&&>
{
X();
};
X<int&&> a;
/usr/bin/ld: /usr/lib/debug/usr/lib/crt1.o(.debug_info): relocation 0 has invalid symbol index 12
...
/usr/lib/gcc/i486-linux-gnu/4.5.1/../../../../lib/crt1.o: In function `_start':
(.text+0x18): undefined reference to `main'
/home/jirka/tmp/ccqJkazZ.o: In function `__static_initialization_and_destruction_0(int, int)':
:(.text+0x1d): undefined reference to `X<int&&>::X()'


I am not sure if you can pass float/double as a template param, its supposed to be a integer only. Also, floating point numbers are not stored as is, so 1.0 is not actually 1.0 but could be 0.999999999999. Thus you should not use floating point numbers while performing comparison.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜