简体   繁体   English

指向 char[] 类型成员的指针的模板签名

[英]template signature for pointer-to-member of type char[]

I've written a comparator to check whether a member of an object is equal to an input.我编写了一个比较器来检查对象的成员是否等于输入。 This works like a charm, except for a member which is a char[];这就像一个魅力,除了一个成员是 char[];

I've searched the internet, the C++ ISO standard and tried a lot, but I can't figure it out.我在互联网上搜索了 C++ ISO 标准并尝试了很多,但我无法弄清楚。

This is the simplified code:这是简化的代码:

/*
 * main.cpp
 *
 *  Created on: Nov 17, 2012
 *      Author: martijn
 */

#include <string.h>

class Data {
public:
    Data() {
        strcpy(Name, "MyCharArray");
    };
    virtual ~Data();

    char Name[12];
};

template <class ClassT, char (ClassT::*Name)[]> // What should be here?!
class Comparator {
public:
    Comparator() {};
    ~Comparator() {};
};

int main() {

    Comparator<Data, &Data::Name> comparatorArray;

    return 0;
}

The problem area (at least that's what I make of it) is indicated in the code.代码中指出了问题区域(至少我是这么认为的)。 The present code is incorrect.当前代码不正确。 The compiler says:编译器说:

Error: could not convert template argument '&Data::Name' to 'char (Data::*)[]'错误:无法将模板参数“&Data::Name”转换为“char (Data::*)[]”

You need to specify the array bound in the template parameter type:需要在模板参数类型中指定绑定的数组:

template <class ClassT, char (ClassT::*Name)[12]>

or possibly:或者可能:

template <class ClassT, std::size_t N, char (ClassT::*Name)[N]>

and used:并使用:

// Note, this is a declaration of a function, is this correct?
Comparator<Data, 12, &Data::Name> comparatorArray();

An easy technique to answer this sort of question is using your compilers error messages.回答此类问题的一种简单技术是使用编译器错误消息。

Create a template function with a generic parameter that blatantly fails to compile when passed your parameter.创建一个带有泛型参数的模板函数,该函数在传递参数时明显无法编译。 Then look at the error message, it usually tells you what T is.然后看错误信息,它通常会告诉你 T 是什么。 My traditional fails to compile is an array of size zero: if your compiler is smart use int x[sizeof(T)-sizeof(expression with the same type as your test var)] but just a zero can work in some lazy compilers.我的传统编译失败是大小为零的数组:如果您的编译器很聪明,请使用int x[sizeof(T)-sizeof(expression with the same type as your test var)]但在一些懒惰的编译器中,只有零可以工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM