我正在寻找的是:我有一个模板化的类,如果该类具有所需的函数,则想调用一个函数,例如:
template<class T> do_something() {
if constexpr (std::is_member_function_pointer<decltype(&T::x)>::value) {
this->_t->x(); // _t is type of T*
}
}
Run Code Online (Sandbox Code Playgroud)
发生的情况:如果T不带功能,则编译器不会编译。小例子:
#include <type_traits>
#include <iostream>
class Foo {
public:
void x() { }
};
class Bar { };
int main() {
std::cout << "Foo = " << std::is_member_function_pointer<decltype(&Foo::x)>::value << std::endl;
std::cout << "Bar = " << std::is_member_function_pointer<decltype(&Bar::x)>::value << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编译器说:
is_member_function_pointer.cpp:17:69: error: no member named 'x' in 'Bar'; did you mean 'Foo::x'?
std::cout << "Bar …Run Code Online (Sandbox Code Playgroud) 我有一个cpp问题,我不知道什么是错的..也许你可以帮助我:).我正在尝试为图形实现数据结构.在此图中,我将连接一些节点,这些节点具有较小的欧氏距离,但在第二次迭代时,我的迭代器将指向0x0.如果我将这两个节点的距离给予std :: cout,则只出现这种情况.这是我的代码:
for(vector<Node*>::iterator n1 = g->getNodes().begin(); n1 != g->getNodes().end(); ++n1)
{
for(vector<Node*>::iterator n2 = g->getNodes().begin(); n2 != g->getNodes().end(); ++n2)
{
if(*n2 == 0)
{
// This will be entered after the first iteration of n2.
cout << "n2 null" << endl;
continue;
}
double distance = (*n1)->getDistance(*n2); // just euclidean distance
if(distance <= minDistance)
{
// This works fine:
cout << "(" << *n1 << "," << *n2 << ") << endl;
// This brings me a "Segmentation fault" …Run Code Online (Sandbox Code Playgroud)