这是相应的问题,我想知道的是,是否有可能通过成员函数将全局函数引入重载决策?
我试过两种方式,但都不起作用:
void foo(double val) { cout << "double\n";}
class obj {
public:
using ::foo; // (1) compile error: using-declaration for non-member at class scope
void callFoo() {
using ::foo; // (2?will cause the global version always be called
foo(6.4);
foo(0);
}
private:
void foo(int val) {cout << "class member foo\n"; }
};
Run Code Online (Sandbox Code Playgroud) 我有课:
template <typename val_t>
class tracer_t : public base_tracer_t<val_t> {
std::vector<std::string> m_trace;
public:
virtual void push_fact(val_t fact) override {
std::string str = "+ fact: " + to_string(fact);
m_trace.push_back(std::move(str));
}
virtual void push_rule(const std::string &id, val_t val, bool tg) override {
std::string str = "+ ";
if (tg) { str += "target: "; }
else { str += "rule: "; }
str += id + " -> " + to_string(val);
m_trace.push_back(std::move(str));
}
virtual void print() override {
std::cout << "Stack trace: …
Run Code Online (Sandbox Code Playgroud) 我有一个容器,并希望依赖于使用我的库的人来确保函数可用于基础value_type(即将到来的示例中的pow()).我希望编译器根据其签名在具有相同名称的成员函数内使用该函数.
我试图创建一个最小的例子:
#include <iostream>
#include <cmath>
using std::pow;
template <typename T>
struct container {
T value;
container<T> pow(T const exp) const {
return {pow(this->value, exp)};
}
};
int main() {
container<double> value{81.};
std::cout << value.value << "^0.25 = " << value.pow(.25).value << '\n';
return 0;
}
Run Code Online (Sandbox Code Playgroud)
所述容器<>提供POW()方法,是应该依靠POW()是可从在全局命名空间的基础类型.
这应该有助于使用自定义数字类型.即图书馆用户应该能够定义他们自己的类型,类似于数字,并为其类型提供pow()函数,使其容器<>兼容.
问题,clang和gcc都没有从全局命名空间中获取函数:
c++ -std=c++11 pow.cpp -o pow
pow.cpp:11:28: error: too many arguments to function call, expected single argument 'exp', …
Run Code Online (Sandbox Code Playgroud)