Yuu*_*shi 4 c++ templates enable-if c++11
这是我正在尝试做的一个减少的例子:
#include <string>
#include <iostream>
#include <type_traits>
template <typename T>
class foo
{
public:
template <typename U>
typename std::enable_if<std::is_same<T, U>::value>::type
bar(const U& t)
{
std::cout << t << "\n";
}
};
template <typename... Args>
class baz
: public foo<Args>...
{
};
int main()
{
baz<double, std::string> b;
b.bar(1.0);
}
Run Code Online (Sandbox Code Playgroud)
这给了我模糊的函数错误:
Run Code Online (Sandbox Code Playgroud)error: request for member 'bar' is ambiguous b.bar(1.0); note: candidates are: template<class U> typename std::enable_if<std::is_same<T, U>::value>::type foo<T>::bar(const U&) [with U = U; T = std::basic_string<char>] note: template<class U> typename std::enable_if<std::is_same<T, U>::value>::type foo<T>::bar(const U&) [with U = U; T = double]
我的问题有两个:
U
不推导出内部模板?我认为这是由于模板推导和重载解析的排序,但有人可以解释一下吗?我认为错误信息具有误导性.问题实际上是名称bar
在多个基类中可用,并且您没有使用using
指令将所需的名称带入派生类范围.
这是一个有效的解决方案:
template <typename X, typename... Args>
class baz : public foo<X>, public baz<Args...>
{
public:
using foo<X>::bar; //bring the name from the first base
using baz<Args...>::bar; //bring the name from the second base
};
template <typename X>
class baz<X> : public foo<X> //specialization for one argument
{
//no using directive needed, as there is one base only!
};
Run Code Online (Sandbox Code Playgroud)