本文介绍了如何让C ++知道运算符已经为一个类重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以编写一个模板函数,对于某个特定类型的类有一些函数或重载运算符?例如

Is it possible to write a template function for which a particular type of classes have some functions or overloaded operators? For instance

template <typename T>
void dosomething(const T& x){
    std::cout << x[0] << std::endl;
}



在本上下文中,我假设x是一个类,数组,也就是说,我已经重载了 [] 运算符以及< 使用 std :: cout

我的实际代码略有不同,但gcc给了我

The actual code that I have is slightly different but gcc is giving me

error: subscripted value is neither array nor pointer

这必须是因为它不知道我期望 T 是重载 [] 运算符的一些类。有谁知道是否可以克服这一点?我想让c ++知道特定的类型 T 会有 [] 重载。

This must be because it doesn't know that I'm expecting T to be of some class that overloads the [] operator. Does anyone know if it is possible to overcome this? I'd like to let c++ know that the particular type T will have the [] overloaded.

推荐答案

您可能需要提供更多细节,因为这个简短示例适用于我:

You might need to provide a little more detail, as this short example works for me:

#include <iostream>
#include <vector>

template <typename T>
void dosomething(const T& x){
    std::cout << x << std::endl;
}

template <typename T>
void dosomething_else(const T& x){
    std::cout << x[0] << std::endl;
}

int main() {
    dosomething< int >(1) ;
    std::vector< int > vec( 3, 1 );
    //dosomething< std::vector< int > >(vec);
    dosomething_else< std::vector< int > >(vec);
}

然而,如果你取消注释这行,你会得到一个编译错误std :: vector不实现<<操作符:

However, if you were to uncomment this line you would get a compiler error as std::vector doesn't implement the << operator:

//dosomething< std::vector< int > >(vec);

当你说这个想法是在正确的轨道:

When you say this your thinking is on the right track:

然而,C ++编译器实际上会在编译时搜索任何请求它的函数的[]操作符。如果没有定义[]运算符,则会出现编译错误。例如,如果插入到main()函数中,这将导致编译器错误:

However, the C++ compiler will actually search for [] operator at compile-time for any functions that request it. If there is no [] operator defined, you will get a compiler error. For example, this will cause a compiler error if inserted into the main() function:

dosomething_else< int >(1);

您收到此错误讯息,类似于您在问题中的建议:

You get this error message, similar to what you suggest in the question:

test.cpp: In function 'void dosomething_else(const T&) [with T = int]':
test.cpp:19:   instantiated from here
test.cpp:11: error: subscripted value is neither array nor pointer

您可以使用此问题中概述的方法在编译时检查是否存在[]:

You can actually check if the [] exists at compile-time using the method outlined in this question:How to check whether operator== exists?

这篇关于如何让C ++知道运算符已经为一个类重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 08:53