使用std :: enable_if和variadic基类

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)

这给了我模糊的函数错误:

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]
Run Code Online (Sandbox Code Playgroud)

我的问题有两个:

  1. 为什么U不推导出内部模板?我认为这是由于模板推导和重载解析的排序,但有人可以解释一下吗?
  2. 还有另一种方法可以解决我想要做的事情吗?

Naw*_*waz 5

我认为错误信息具有误导性.问题实际上是名称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)

完成演示

  • 那么类模板可以从自身继承吗?那是新的!:) (2认同)