C++ template non-type parameter type deduction

自闭症网瘾萝莉.ら 提交于 2020-01-14 07:38:27

问题


I'am trying to do this work:

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

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

The purpose is to simplify a much more complex template.

After many searches, I don't find any way to do that on C++0x, so stackoverflow is my last resort.

  • without specify all type of T possible...
  • I am on g++ C++0x, so sexy stuff is allowed.

回答1:


C++0x introduces decltype(), which does exactly what you want.

int main()
{
  f<decltype(10), 10>(); // will become f<int, 10>();
  return 0;
}



回答2:


There is no automatic template deduction for structs/classes in C++. What you can do though is something like this (warning, untested!):

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

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

int             main()
{
    F(10)();
    return (0);
}

It is not as clean as template only code but it's clear what it does and allows you to avoid the burden of repeating yourself. If you need it to work on non-C++0x compilers, you can use Boost.Typeof instead of decltype.




回答3:


I don't think you can do that, you simply need to let the compiler know that there is a type there. The closest thing I can think of is something like this:

template <class T>
void f(T x) {
    // do something with x
}

f(10);

Beyond that, I suppose you could just assume a bit and do something like this:

template<size_t x>
void f() {

}

f<10>();

Neither of which is quite what you want, but a decent compiler should be able to make a lot of this compile time anyway since you are passing a constant.

Can you elaborate on what you are trying to accomplish? Are non-integer types going to be allowed? Why don't you show us the more complicated template you are trying to simplify.



来源:https://stackoverflow.com/questions/6737374/c-template-non-type-parameter-type-deduction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!