2017-01-12 1 views
0

저는 상속받은 클래스 집합을 작업하면서 템플릿은 템플릿이 아니고 보호 된 생성자이며 멤버 변수가없는 순수 가상 메서드입니다.이 클래스는 선언의 역할을합니다. 실제 상속 된 템플릿 클래스가 포함 할 필요가있는 것.C++ 클래스를 인스턴스화 할 때 템플릿 인수에 기본값을 할당하는 방법

상속받은 버전에서는 저장된 문자 배열의 크기를 설정하는 데 하나의 템플릿 인수 size_t 만 있으므로 template<size_t fixed_size>이라는 접두사를 사용해야합니다. 그것에는 두 개의 전용 멤버 이 있습니다. 하나의 매개 변수를 제외하고는 유효한 생성자 중 하나가 전달한 문자열의 크기를 포함합니다. 그래서이 변수를 static const size_t으로 만들고 다른 변수로는 char[][size_t + 1]으로 설정하려고합니다. 내가 무엇을하고 싶습니다 static const size_t의 구성원 변수를 인스턴스화 자체가 아니라 설정할 수 있지만 해당 생성자가 호출 될 때 크기가 char[], char* 또는 std::string.size() 그것의 유효한 생성자. fixed_string<some value> myString("hello");은 차라리 대신이 작업을 수행 할 것이다 : 내가 컴파일 할 때

#include <string> 

// This base class does not contain any member variables 
// and no implementations of any constructor or function 
// it serves as a definition to your interface as well as 
// defining what methods must be implemented. 
class fixed_string_base { 
protected: 
    // The types of constructors you want to implement 
    explicit fixed_string_base(char words[]) {}; 
    explicit fixed_string_base(const char* words) {} 
    explicit fixed_string_base(const std::string words) {}  

    // The types of things you want to leave to default 
    fixed_string_base() = default; 
    fixed_string_base(fixed_string_base const&) = default; 
    fixed_string_base(fixed_string_base&&) = default; 
    fixed_string_base& operator=(fixed_string_base const&) = default; 
    fixed_string_base& operator=(fixed_string_base&&) = default; 
    virtual ~fixed_string_base() = default; 
public: 
    // Put all of your pure virtual methods here that fixed_string must implement; 
    virtual char* c_str() = 0; 
}; 

// This is the actual class that inherits from its non 
// templated declaration interface. 
template<size_t fixed_size> 
class fixed_string : public fixed_string_base { 
private: 
    static const size_t fixed_string_size_ = fixed_size + 1; 
    char fixed_string_[ fixed_string_size_ ]; 

public: 
    // Experimental not sure how to set the fixed_string_size_ from the size of the array passed in to the constructors 
    explicit fixed_string(char words[]) : fixed_string_size_(sizeof(words) + 1) { 
     fixed_string_ = words; 
     fixed_string_[fixed_size] = '\0'; 
    } 
    explicit fixed_string(const char* words) : fixed_string_size_(sizeof(words) + 1) { 
     fixed_string_ = words; 
     fixed_string_[fixed_size] = '\0'; 
    } 
    explicit fixed_string(const std::string& words) : fixed_string_size(words.size() + 1) { 
     fixed_string_ = words.c_str(); 
     fixed_string_[fixed_size] = '\0'; 
    } 

    virtual char* c_str() { return fixed_string_; } 

    // Defaulted Constructors and Operators 
    fixed_string(fixed_string const&) = default; 
    fixed_string(fixed_string&&) = default; 
    fixed_string& operator=(fixed_string const&) = default; 
    fixed_string& operator=(fixed_string&&) = default; 
    virtual ~fixed_string() = default; 
}; 

: fixed_string myString("hello");를 여기 내 클래스가 현재처럼 무엇을 내가 클래스의 인스턴스를 갈 때 또한 나는이 다음을 수행하지 않으려는 이 내가지고있어 오류입니다 :

1>------ Build started: Project: FileTester, Configuration: Debug Win32 ------ 
1> main.cpp 
1>c:\users\skilz80\documents\visual studio 2015\projects\filetester\filetester\main.cpp(71): error C2438: 'fixed_string_size_': cannot initialize static class data via constructor 
1> c:\users\skilz80\documents\visual studio 2015\projects\filetester\filetester\main.cpp(71): note: while compiling class template member function 'fixed_string<5>::fixed_string(const char *)' 
1> c:\users\skilz80\documents\visual studio 2015\projects\filetester\filetester\main.cpp(103): note: see reference to function template instantiation 'fixed_string<5>::fixed_string(const char *)' being compiled 
1> c:\users\skilz80\documents\visual studio 2015\projects\filetester\filetester\main.cpp(103): note: see reference to class template instantiation 'fixed_string<5>' being compiled 
1>c:\users\skilz80\documents\visual studio 2015\projects\filetester\filetester\main.cpp(72): error C3863: array type 'char [6]' is not assignable 
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ========== 

내가 종류의 컴파일러 오류가 주장하는 것을 이해하지만이 클래스를 구현 완료를 해결하는 방법에 대한 확실하지 않다. auto 또는 심지어 lambda 기술과 같이 여기에 도움이 될 VS2015 CE 컴파일러의 새로운 기능이 있습니까? 나는 내가 뭘 바라 보는 지 모르겠다. 모든 팁, 제안 또는 도움을 매우 극명하게 될 것입니다.

답변

1

당신은

template <std::size_t N> 
fixed_string<N> make_fixed_string(const char(&s)[N]) 
{ 
    return fixed_string<N>(s); 
} 

그래서 당신은 당신이 strncpy을 할 필요가로 C 배열의 카피 없기 때문에 당신이, 당신의 생성자를 수정하자

auto s = make_fixed_string("Hello"); 

을 할 수 할 수 있습니다.

+0

생각할 수도 있지만, 힙에 할당하지 않아도되도록 노력하고 또한 일단 이것이 구성되면 문자열이 고정되어 수정할 수 없으며 값만 반환 할 수 있습니다. '=='이거나 다른 고정 된 문자열과 비교할 수 있습니다. –

+1

할당하지 않고 RVO 및 복사 elision은 괜찮은 컴파일러에서 발생해야합니다. 문자열을'const'로하고 싶다면 여전히'const'를 추가 할 수 있습니다 : const auto s = make_fixed_string ("Hello");'. – Jarod42

+0

글쎄, 내가 힙에 할당하고 싶을 수도 있지만, 그렇지 않은 경우가있을 수 있습니다. 그래서 나를 위해 자동으로 할 수있는 편리한 클래스를 작성하려고합니다. 기본적으로 생성자에서 전달 된 값에 따라 설정되는'const char [fixed_size] '에 대한 래퍼입니다. 'std :: string'도 상속 받고 싶지는 않지만'std :: string'을 유효한 매개 변수 또는 입력으로 받아 들일 수는 있습니다. –

관련 문제