不明确的函数调用到C ++基类 [英] Ambiguous Function Calls to C++ base classes
问题描述
我想创建一个可变模板类,为类型列表中的每个类提供一个方法。下面显示一个例子,它为类型串中的每个类创建一个 print
方法:
I'm trying to create a variadic templated class which provides a method for each class in the typelist. An example is shown below which creates a print
method for every class in the typelist:
#include <iostream>
#include <string>
// Helper class providing a function call
template <typename T>
class PrintHelper
{
public:
void print(const T& t) { std::cout << t << std::endl; }
};
// Provides a print method for each type listed
template <typename... Ts>
class Printer : public PrintHelper<Ts>...
{};
int main()
{
Printer<int, std::string> p;
p.print(std::string("Hello World")); // Ambiguous Call
}
注释行会导致GCC 4.6.3错误在注释行。
The commented line results in an error from GCC 4.6.3 on the commented line. What is the correct way to resolve the ambiguity or should I be looking at a different design?
推荐答案
我不喜欢回答的问题是什么是解决歧义的正确方法?我自己的问题,但是我从这里的评论创建了以下解决方案。它将所有 print
函数带入范围,并允许对所有函数进行C ++重载解析。
I don't like answering my own question but I've created the following solution from the comments here. It brings all print
functions into scope and allows for C++ overload resolution on all of the functions.
#include <iostream>
#include <string>
// Helper class providing a function call
template <typename T>
class PrintHelper
{
public:
void print(const T& t) { std::cout << t << std::endl; }
};
// Provides a print method for each type listed
template <typename... Ts>
class Printer
{};
template<typename T>
class Printer<T> : public PrintHelper<T>
{
public:
using PrintHelper<T>::print;
};
template<typename T, typename... Ts>
class Printer<T, Ts...>: public PrintHelper<T>, public Printer<Ts...>
{
public:
using PrintHelper<T>::print;
using Printer<Ts...>::print;
};
int main()
{
Printer<int, std::string> p;
p.print("Hello World"); // Not an ambiguous Call
}
这篇关于不明确的函数调用到C ++基类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!