当涉及到"问题线"的"隐藏特征"时,没有C++的爱吗?想我会把它扔出去.C++的一些隐藏功能是什么?
关于我最近回答的一些评论,在C++中可以使用的其他有用的演员表明,我对C++转换的理解是错误的.只是为了澄清问题,请考虑以下代码:
#include <string>
struct A {
A( const std::string & s ) {}
};
void func( const A & a ) {
}
int main() {
func( "one" ); // error
func( A("two") ); // ok
func( std::string("three") ); // ok
}
Run Code Online (Sandbox Code Playgroud)
我的断言是第一个函数调用是一个错误,因为没有从const char*到A的转换.有一个从字符串到A的转换,但是使用它会涉及多个转换.我的理解是这是不允许的,这似乎是由g ++ 4.4.0和Comeau编译器证实的.使用Comeau,我收到以下错误:
"ComeauTest.c", line 11: error: no suitable constructor exists
to convert from "const char [4]" to "A"
func( "one" ); // error
Run Code Online (Sandbox Code Playgroud)
如果您可以指出我错在哪里,无论是在这里还是在原始答案中,最好是参考C++标准,请这样做.
而C++标准的答案似乎是:
最多一个用户定义的转换(构造函数或转换函数)隐式应用于单个值.
感谢Abhay提供报价.
struct Bob
{
template<class T>
void operator () () const
{
T t;
}
template<class T>
operator T () const
{
T t;
return t;
}
};
Run Code Online (Sandbox Code Playgroud)
我可以像这样直接调用Bob的operator()
Bob b;
b.operator()<int>();
Run Code Online (Sandbox Code Playgroud)
如何使用这样的特定模板参数直接调用转换运算符?
Bob b;
std::string s = b.???<std::string>();
Run Code Online (Sandbox Code Playgroud)
无法使用static_cast
Bob b;
std::string s = static_cast<std::string>(b);
Run Code Online (Sandbox Code Playgroud)
error: call of overloaded ‘basic_string(Bob&)’ is ambiguous
问题 如何直接使用模板参数调用或者它是不可能的.我知道有一些使用包装函数的变通方法.
说我有三个班:
class X{};
class Y{};
class Both : public X, public Y {};
Run Code Online (Sandbox Code Playgroud)
我的意思是说我有两个类,然后是第三个类,它们都扩展了(多重继承).
现在说我在另一个类中定义了一个函数:
void doIt(X *arg) { }
void doIt(Y *arg) { }
Run Code Online (Sandbox Code Playgroud)
我用这两个实例调用这个函数:
doIt(new Both());
Run Code Online (Sandbox Code Playgroud)
这会导致编译时错误,表明函数调用不明确.
有什么情况,除了这个,C++编译器决定调用是不明确的并且抛出错误,如果有的话?编译器如何确定这些情况是什么?
c++ inheritance programming-languages function multiple-inheritance
我想在C++中使用迭代器,它只能迭代特定类型的元素.在以下示例中,我想仅迭代SubType实例的元素.
vector<Type*> the_vector;
the_vector.push_back(new Type(1));
the_vector.push_back(new SubType(2)); //SubType derives from Type
the_vector.push_back(new Type(3));
the_vector.push_back(new SubType(4));
vector<Type*>::iterator the_iterator; //***This line needs to change***
the_iterator = the_vector.begin();
while( the_iterator != the_vector.end() ) {
SubType* item = (SubType*)*the_iterator;
//only SubType(2) and SubType(4) should be in this loop.
++the_iterator;
}
Run Code Online (Sandbox Code Playgroud)
我如何在C++中创建这个迭代器?