C++模板非类型参数类型推导

Gra*_*ind 9 c++ templates metaprogramming c++11

我正努力做这项工作:

template < typename T, T VALUE >
void            f()
{
    /* ... */
}

int             main()
{
    f<10>();    // implicit deduction of [ T = int ] ??
    return (0);
}
Run Code Online (Sandbox Code Playgroud)

目的是简化更复杂的模板.

经过多次搜索,我在C++ 0x上找不到任何方法,所以stackoverflow是我最后的选择.

  • 没有指定所有类型的T可能......
  • 我在g ++ C++ 0x上,所以允许性感的东西.

Sea*_*ean 5

C++ 0x引入decltype(),它完全符合您的要求.

int main()
{
  f<decltype(10), 10>(); // will become f<int, 10>();
  return 0;
}
Run Code Online (Sandbox Code Playgroud)


Kar*_*nek 5

C++中的结构/类没有自动模板推导.你可以做的就是这样(警告,未经测试!):

#define F(value) f<decltype(value), value>

template < typename T, T VALUE >
void            f()
{
    /* ... */
}

int             main()
{
    F(10)();
    return (0);
}
Run Code Online (Sandbox Code Playgroud)

它不像模板专用代码那样干净,但它清楚它的功能,并且可以避免重复自己的负担.如果需要它在非C++ 0x编译器上工作,可以使用Boost.Typeof而不是decltype.