加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何强制C从全局命名空间中选择一个函数?

发布时间:2020-12-16 10:00:26 所属栏目:百科 来源:网络整理
导读:我有一个容器,并希望依赖于使用我的库的人来确保函数可用于基础value_type(即将到来的示例中的pow()).我希望编译器根据其签名在具有相同名称的成员函数内使用该函数. 我试图创建一个最小的例子: #include iostream#include cmathusing std::pow;template ty
我有一个容器,并希望依赖于使用我的库的人来确保函数可用于基础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;
}

容器<>提供了一个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',have 2 arguments
                return {pow(this->value,exp)};
                        ~~~              ^~~
pow.cpp:17:50: note: in instantiation of member function 'container<double>::pow' requested here
        std::cout << value.value << "^0.25 = " << value.pow(.25).value << 'n';
                                                        ^
pow.cpp:10:2: note: 'pow' declared here
        container<T> pow(T const exp) const {
        ^

如果我显式使用全局命名空间,它按预期工作:

container<T> pow(T const exp) const {
    return {::pow(this->value,exp)};
}

该程序产生预期的输出:

c++ -std=c++11 pow.cpp -o pow
./pow
81^0.25 = 3

这解决了实际问题,但我想知道为什么有必要?签名匹配不应该允许编译器选择正确的函数吗?

解决方法

你需要在pow函数中引入std :: pow函数.如果ADL失败,这允许编译器回退到std :: pow

#include <iostream>
#include <cmath>

template <typename T>
struct container {
    T value;

    container<T> pow(T const exp) const {
        using std::pow;
        return {pow(this->value,exp)};
    }
};

int main() {
    container<double> value{81.};
    std::cout << value.value << "^0.25 = " << value.pow(.25).value << 'n';
    return 0;
}

Live Example

这与building a custom swap function时的操作相同.您可以看到它与具有自己的pow here的类一起工作

编辑那些不了解查找的人.了解它们之间的区别非常重要

T func(T a,T b)
{
  using std::pow;
  return pow(a,b);
}

T func(T a,T b)
{
  return std::pow(a,b);
}

后者总是调用std :: pow(),如果T不能转换为double(或者std :: complex< double>如果< complex>是#included),则会失败.前者将使用ADL找到最匹配的pow()函数,它可能是std :: pow.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读