开发者

Problem with function template without <>

Is there anyway I can do this without writing func2<int>();

int func() { return 5; }

template<class T>
T func2() { return func(); }


int main()
{
    auto k = func2开发者_如何学Go();
    //auto k = func2<int>();

    return 0;
}


No, because the template argument can not be deduced. You need to specify it, how else would the compiler know what to substitute it with? int? double? A user-defined type?
Edit
If you're already using C++0x (I assume so because of auto), you can use the new trailing return type function style:

auto func2() -> decltype(func()) {
  return func();
}

decltype(func()) would get the return type of func, without actually calling it.
Edit2
Okay, you don't even need the trailing return type, a simple decltype does the job too:

decltype(func()) func2() { return func(); }

The trailing return type is more useful for situations where the return depends on some or all of the parameters, and especially if they're templated. See here for a nice explanation.


Perhaps you are looking for something like that:

int func() { return 5; }

auto func2() -> decltype( func() )
{
  return func();
}

int main()
{
  auto k = func2();
}

However, I don't understand why you made func2 a template, since you always want it to return an int. It could be useful if you wanted to cast the result of func to another type, but in this case you would need to specify explicitely the type you want as a return.


No, there is no way to do this. The compiler has no way of deducing the template argument since it does not consider the return type for that.

If you are willing to relent and use int k instead of auto k then you can use a “cheat” to achieve the same goal by returning a proxy object that has an implicit conversion to typename T.


The compiler is not able to deduce the template argument type from the return type you are assigning to. You are not giving any hint to the compiler what the return type could be. Therefore, any template argument types which cannot be deduced need to be explicitly specified.


You can achieve this syntax with c++03 if you use int instead of auto:

int func() { return 5; }

template<class T> T func2() { return func(); }


struct Inference {
    template<typename T> operator T () { return func2<T>(); }
};

int main() {
  int k = Inference();
}

EDIT: nvm, Konrad Rudolph's answer already said this.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜