考虑以下简单类(请不要争论有用性):
class Container
{
public:
Container(const long long &val); //construct the container with a long long
Container(const long double &val); //construct the container with a long double
Container(const std::string &val); //construct the container with a string
Container(const Container &val); //copy constructor, implemented as copy and swap
//explicit conversions are also included for other data types
explicit operator long long() const; //explicit conversion to long long
private:
int dataType;
void *data;
};
为了构建对象,我会调用:
Container cont(20); //or
Container cont2("some string");
但是编译器告诉我他无法解析对 int 的模糊构造函数调用。
这引出了我的问题,什么是解决这种歧义的最好和最干净的方法。
我应该使用某种看起来像这样的模板化构造函数吗:
Container<int> cont(20);
或者使用显式转换或虚拟参数?
模板化方式看起来像是我可以接受的折衷方案,但我确信实际调用看起来会有所不同。
谢谢您的任何见解!
最佳答案
只需为 int
添加一个构造函数来消除它的歧义:
Container(int i)
: Container(static_cast<long long>(i)) // or whichever version you want
// to call
{ }
关于C++ - 如何解决函数重载歧义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31434420/